/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sjtu.bean;

import com.sjtu.database.DataBase;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author p w
 */
public class LabelBean {

    private int id;
    private String content;

    public LabelBean(int id, String content) {
        this.id = id;
        this.content = content;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public static LabelBean getLabel(int labelId) {
        try {
            DataBase database = DataBase.getInstance();
            ResultSet rs = database.query("select * from book where id = '" + labelId + "';");
            LabelBean label = setLabel(rs);
            rs.close();
            return label;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static LabelBean setLabel(ResultSet rs) {
        try {
            if (rs == null || !rs.next()) {
                return null;
            }
            return new LabelBean(rs.getInt("id"), rs.getString("content"));
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static LabelBean addLabel(String content) {
        try {
            DataBase database = DataBase.getInstance();
            ResultSet rs = database.query("select * from booklabel where content = '" + content + "';");
            if (rs.next()) {
                return new LabelBean(rs.getInt("id"),content);
            }
            String sql = "insert into booklabel (content) values ('" + content + "');";
//            System.out.println(sql);
            database.update(sql);
            rs = database.query("select * from booklabel where content = '" + content + "';");
            if (rs.next()) {
                return new LabelBean(rs.getInt("id"),content);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
